package cn.wh.pet.service.impl;

import cn.wh.pet.domain.Pet;
import cn.wh.pet.domain.PetType;
import cn.wh.pet.mapper.PetTypeMapper;
import cn.wh.pet.service.IPetTypeService;
import cn.wh.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2022-06-25
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> queryTree() {
        //找到所有petType的数据
        List<PetType> petTypes = petTypeMapper.loadAll();
        //为了后面找到自己的父亲,我们这里可以把整体的部门数据转换一份成Map
        Map<Long,PetType> allPets = new HashMap<>();
        for (PetType petType : petTypes) {
            allPets.put(petType.getId(), petType);
        }
        List<PetType> firstpets = new ArrayList<>();
        for (PetType tmp : petTypes) {
            if (tmp.getPid() == null){
                firstpets.add(tmp);
            }else{
                PetType parent = allPets.get(tmp.getPid());
                if (parent != null){
                    parent.getChildren().add(tmp);
                }
            }
        }
        return firstpets;
    }
}
